'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Comment, CommentFormData, ApiResponse, PaginationParams, PaginationResponse } from './types'
import { API_REQUESTS } from './config'

export default function CommentsPage() {
  const [comments, setComments] = useState<Comment[]>([])
  const [newComment, setNewComment] = useState('')
  const [author, setAuthor] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [pagination, setPagination] = useState<PaginationResponse>({
    pageIndex: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  })
  const router = useRouter()

  // 获取留言列表
  const fetchComments = async (pageIndex: number = 1, append: boolean = false) => {
    try {
      // 构建请求参数
      const requestBody: PaginationParams = {
        pageIndex,
        pageSize: 10
      }
      
      const response = await fetch(API_REQUESTS.LIST_COMMENTS.url, {
        method: API_REQUESTS.LIST_COMMENTS.method,
        headers: API_REQUESTS.LIST_COMMENTS.headers,
        body: JSON.stringify(requestBody)
      })
      
      if (response.ok) {
        const data = await response.json()
        const newComments = data.comments || data.data || []
        
        if (append) {
          // 追加数据
          setComments(prev => [...prev, ...newComments])
        } else {
          // 替换数据
          setComments(newComments)
        }
        
        // 更新分页信息
        setPagination({
          pageIndex: data.pageIndex || pageIndex,
          pageSize: data.pageSize || 10,
          total: data.total || 0,
          totalPages: data.totalPages || 0
        })
      } else {
        console.error('获取留言失败:', response.status, response.statusText)
      }
    } catch (error) {
      console.error('获取留言失败:', error)
    } finally {
      setIsLoading(false)
      setIsLoadingMore(false)
    }
  }

  // 提交新留言
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newComment.trim() || !author.trim()) {
      alert('请填写留言内容和昵称')
      return
    }

    setIsSubmitting(true)
    try {
      const response = await fetch(API_REQUESTS.CREATE_COMMENT.url, {
        method: API_REQUESTS.CREATE_COMMENT.method,
        headers: API_REQUESTS.CREATE_COMMENT.headers,
        body: JSON.stringify({
          content: newComment,
          username: author,
        }),
      })

      if (response.ok) {
        const result = await response.json()
        setNewComment('')  // 只清空评论内容
        // 移除setAuthor('')，保留昵称
        fetchComments()  // 重新获取留言列表
        alert('留言提交成功！')
      } else {
        const errorData = await response.json().catch(() => ({}))
        alert(`留言提交失败：${errorData.message || '请重试'}`)
      }
    } catch (error) {
      console.error('提交留言失败:', error)
      alert('留言提交失败，请重试')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 加载更多留言
  const handleLoadMore = async () => {
    if (isLoadingMore) return
    
    const nextPage = pagination.pageIndex + 1
    if (nextPage > pagination.totalPages) return
    
    setIsLoadingMore(true)
    await fetchComments(nextPage, true)
  }

  // 删除留言（如果外部 API 支持的话）
  const handleDelete = async (commentId: string) => {
    if (!confirm('确定要删除这条留言吗？')) return

    try {
      // 注意：这里需要根据实际的外部 API 来调整
      // 如果外部 API 不支持删除，可以隐藏删除按钮
      const deleteConfig = API_REQUESTS.DELETE_COMMENT(commentId)
      const response = await fetch(deleteConfig.url, {
        method: deleteConfig.method,
        headers: deleteConfig.headers,
      })

      if (response.ok) {
        fetchComments(1, false) // 重新获取留言列表
        alert('删除成功！')
      } else {
        alert('删除失败，请重试')
      }
    } catch (error) {
      console.error('删除留言失败:', error)
      alert('删除失败，请重试')
    }
  }

  useEffect(() => {
    fetchComments(1, false)
  }, [])

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  const getBrowserInfo = (userAgent: string) => {
    if (userAgent.includes('Chrome')) return 'Chrome'
    if (userAgent.includes('Firefox')) return 'Firefox'
    if (userAgent.includes('Safari')) return 'Safari'
    if (userAgent.includes('Edge')) return 'Edge'
    if (userAgent.includes('Opera')) return 'Opera'
    return '未知浏览器'
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* 页面标题 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            博客留言板
          </h1>
          <p className="text-gray-600 dark:text-gray-400">
            欢迎留下您的想法和评论
          </p>
        </div>

        {/* 新增留言表单 */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-8">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
            发表留言
          </h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="author" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                昵称 *
              </label>
              <input
                type="text"
                id="author"
                value={author}
                onChange={(e) => setAuthor(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                placeholder="请输入您的昵称"
                required
              />
            </div>
            <div>
              <label htmlFor="content" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                留言内容 *
              </label>
              <textarea
                id="content"
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                rows={4}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                placeholder="请输入您的留言内容..."
                required
              />
            </div>
            <div className="flex justify-end">
              <button
                type="submit"
                disabled={isSubmitting}
                className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isSubmitting ? '提交中...' : '发表留言'}
              </button>
            </div>
          </form>
        </div>

        {/* 留言列表 */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-6">
            留言列表 ({comments.length})
          </h2>
          
          {isLoading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
              <p className="text-gray-600 dark:text-gray-400 mt-2">加载中...</p>
            </div>
          ) : comments.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-gray-600 dark:text-gray-400">暂无留言，快来发表第一条留言吧！</p>
            </div>
                     ) : (
             <div className="space-y-6">
               {comments.map((comment) => (
                 <div key={comment.id} className="border-b border-gray-200 dark:border-gray-700 pb-6 last:border-b-0">
                   <div className="flex justify-between items-start mb-3">
                     <div className="flex items-center space-x-2">
                       <span className="font-medium text-gray-900 dark:text-white">
                         {comment.username}
                       </span>
                       <span className="text-sm text-gray-500 dark:text-gray-400">
                         {formatDate(comment.created_at)}
                       </span>
                     </div>
                     {/* 如果外部 API 不支持删除，可以隐藏这个按钮 */}
                     {/* <button
                       onClick={() => handleDelete(comment.id)}
                       className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 text-sm"
                     >
                       删除
                     </button> */}
                   </div>
                   
                   <div className="text-gray-800 dark:text-gray-200 mb-3">
                     {comment.content}
                   </div>
                   {comment.extradata?
                   <div className="flex items-center space-x-4 text-xs text-gray-500 dark:text-gray-400">
                     {comment.extradata.ip?<span>IP: {comment.extradata.ip}</span>:null}
                     {comment.extradata.device?<span>浏览器: {comment.extradata.browser}</span>:null}
                     {comment.extradata.os?<span>系统: {comment.extradata.os}</span>:null}
                     {comment.extradata.device_type?<span>设备类型: {comment.extradata.device_type}</span>:null}
                   </div>
                   :null}
                 </div>
               ))}
               
               {/* 展示更多按钮 */}
               {pagination.pageIndex < pagination.totalPages && (
                 <div className="text-center pt-6">
                   <button
                     onClick={handleLoadMore}
                     disabled={isLoadingMore}
                     className="px-6 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                   >
                     {isLoadingMore ? (
                       <div className="flex items-center space-x-2">
                         <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-600"></div>
                         <span>加载中...</span>
                       </div>
                     ) : (
                       '展示更多'
                     )}
                   </button>
                   <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                     第 {pagination.pageIndex} 页，共 {pagination.totalPages} 页 ({pagination.total} 条留言)
                   </p>
                 </div>
               )}
             </div>
           )}
        </div>
      </div>
    </div>
  )
} 